package com.quartz.service.impl;

import com.quartz.bean.SysTask;
import com.quartz.service.IJobManageService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description 任务管理实现
 * @Author LCXU
 * @Date 2020/12/25 11:24
 * @Version 1.0
 */
@Service
@Slf4j
public class JobManageService implements IJobManageService {

    @Autowired
    private Scheduler scheduler;

    public boolean addJob(SysTask sysTask) throws Exception {

        Date date = sysTask.getBeginTime();

        if (!CronExpression.isValidExpression(sysTask.getCron())) {
            throw new Exception("表达式不正确");   //表达式格式不正确
        }
        JobDetail jobDetail = null;
        Class jobClass = Class.forName(sysTask.getClazzName());
        jobDetail = JobBuilder.newJob(jobClass).withIdentity(sysTask.getJobName(), sysTask.getJobGroup()).build();

        //表达式调度构建器(即任务执行的时间,不立即执行)
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(sysTask.getCron()).withMisfireHandlingInstructionDoNothing();

        //按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(sysTask.getJobName(), sysTask.getJobGroup()).startAt(date)
                .withSchedule(scheduleBuilder).build();

        //传递参数 这里可以传递参数，在任务执行的时候可以获取参数
        if (sysTask.getParmas() != null && !"".equals(sysTask.getParmas())) {
            trigger.getJobDataMap().put("invokeParam", sysTask.getParmas());
        }
        scheduler.scheduleJob(jobDetail, trigger);
        // pauseJob(sysTask.getJobName(),sysTask.getJobGroup());
        return true;
    }

    public String getJobState(String jobName, String jobGroup) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(jobName, jobGroup);
        return scheduler.getTriggerState(triggerKey).name();
    }

    public boolean pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
        return true;
    }

    public boolean pauseJob(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return false;
        } else {
            scheduler.pauseJob(jobKey);
            return true;
        }

    }

    public boolean resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
        return true;
    }

    public boolean resumeJob(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return false;
        } else {
            scheduler.pauseJob(jobKey);
            return true;
        }
    }

    public boolean deleteJob(SysTask sysTask) throws SchedulerException {
        JobKey jobKey = new JobKey(sysTask.getJobName(), sysTask.getJobGroup());
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            log.error("jobDetail is null");
            return false;
        } else if (!scheduler.checkExists(jobKey)) {
            log.error("jobKey is not exists");
            return false;
        } else {
            scheduler.deleteJob(jobKey);
            return true;
        }

    }

    public boolean modifyJob(SysTask sysTask) throws Exception {
        if (!CronExpression.isValidExpression(sysTask.getCron())) {
            throw new Exception("Illegal cron expression");
        }
        TriggerKey triggerKey = TriggerKey.triggerKey(sysTask.getJobName(), sysTask.getJobGroup());
        JobKey jobKey = new JobKey(sysTask.getJobName(), sysTask.getJobGroup());
        if (scheduler.checkExists(jobKey) && scheduler.checkExists(triggerKey)) {
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            //表达式调度构建器,不立即执行
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(sysTask.getCron()).withMisfireHandlingInstructionDoNothing();
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                    .withSchedule(scheduleBuilder).build();
            //修改参数
            if (!trigger.getJobDataMap().get("invokeParam").equals(sysTask.getParmas())) {
                trigger.getJobDataMap().put("invokeParam", sysTask.getParmas());
            }
            //按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
            return true;
        } else {
            log.error("job or trigger not exists");
            return false;
        }

    }
}
